import { FastifyRequest } from 'fastify';
import { createWriteStream } from 'fs';
import { resolve } from 'path';
import { config } from '@ai/config';
import { Controller, Delete, Param, Post, Req } from '@nestjs/common';
import { Public } from '@/utils/metadata/public';
import { UploadService } from './upload.service';

const { SERVER_PORT } = config;

@Public()
@Controller('upload')
export class UploadController {
    constructor(private readonly uploadService: UploadService) {}

    // @Post()
    // @UseInterceptors(
    //     FilesInterceptor('file', 10, {
    //         storage: diskStorage({
    //             destination: (req, file, cb) => {
    //                 const path = resolve(process.cwd(), 'public');
    //                 return cb(null, path);
    //             },
    //             filename: (req, file, cb) => {
    //                 const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    //                 const ext = extname(file.originalname);
    //                 const filename = basename(file.originalname, ext);
    //                 cb(null, filename + '-' + uniqueSuffix + ext);
    //             },
    //         }),
    //     })
    // )
    // uploadFile(@UploadedFiles() files: Express.Multer.File[], @Req() req: Request) {
    //     return files.map((file) => ({
    //         filename: file.filename,
    //         url: `${req.protocol}://${req.get('host')}/assets/${file.filename}`,
    //     }));
    // }
    @Post()
    async uploadFile(@Req() req: FastifyRequest) {
        const fileList = req.files();
        const ret = [];

        for await (const file of fileList) {
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
            const filename = uniqueSuffix + '-' + file.filename;
            const pathName = resolve(process.cwd(), 'public', filename);
            const writeStream = createWriteStream(pathName);
            file.file.pipe(writeStream);
            ret.push({
                filename: file.filename,
                url: `${req.protocol}://${req.hostname}:${SERVER_PORT}/assets/${filename}`,
            });
        }

        return ret;
    }

    @Delete(':url')
    async remove(@Param('url') url: string) {
        return await this.uploadService.remove(url);
    }
}
